#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h> 

#include "main_gui.h"
#include "image_viewer.h"
#include "commprefs_gui.h"

#define BUFFSIZE 8192

Main_Gui *main_gui;

int prevdepth = 1; //The root level
int currdepth = 1; //The root level

/* Build the gui */
void build_main_gui(void) {
    main_gui = calloc(1, sizeof(Main_Gui));

    /* Main window*/
    main_gui->win = etk_window_new();
    etk_window_title_set(ETK_WINDOW(main_gui->win), "E-Mail");
    etk_window_resize(ETK_WINDOW(main_gui->win), 800, 600);
    etk_container_border_width_set(ETK_CONTAINER(main_gui->win), 5);
    etk_signal_connect_swapped("destroyed", ETK_OBJECT(main_gui->win), ETK_CALLBACK(_main_quit_cb), NULL);

    /* Main container*/
    main_gui->vbox = etk_vbox_new(ETK_FALSE, 0);
    etk_container_add(ETK_CONTAINER(main_gui->win), main_gui->vbox);

    /* Menu bar */
    main_gui->menu_bar = etk_menu_bar_new();
    etk_box_append(ETK_BOX(main_gui->vbox), main_gui->menu_bar, ETK_BOX_START, ETK_BOX_NONE, 0);
    main_gui->menu_item = etk_menu_item_new_with_label("File");
    etk_menu_shell_append(ETK_MENU_SHELL(main_gui->menu_bar), ETK_MENU_ITEM(main_gui->menu_item));

    /* File popup menu */
    main_gui->menu = etk_menu_new();
    etk_menu_item_submenu_set(ETK_MENU_ITEM(main_gui->menu_item), ETK_MENU(main_gui->menu));
    main_gui->popup_menu_item = etk_menu_item_new_with_label("Quit");
    etk_menu_shell_append(ETK_MENU_SHELL(main_gui->menu), ETK_MENU_ITEM(main_gui->popup_menu_item));
    etk_signal_connect("activated", ETK_OBJECT(main_gui->popup_menu_item), ETK_CALLBACK(_main_quit_cb), NULL);

    main_gui->menu_item = etk_menu_item_new_with_label("Edit");
    etk_menu_shell_append(ETK_MENU_SHELL(main_gui->menu_bar), ETK_MENU_ITEM(main_gui->menu_item));
    main_gui->menu_item = etk_menu_item_new_with_label("View");
    etk_menu_shell_append(ETK_MENU_SHELL(main_gui->menu_bar), ETK_MENU_ITEM(main_gui->menu_item));
    main_gui->menu_item = etk_menu_item_new_with_label("Message");
    etk_menu_shell_append(ETK_MENU_SHELL(main_gui->menu_bar), ETK_MENU_ITEM(main_gui->menu_item));
    main_gui->menu_item = etk_menu_item_new_with_label("Tools");
    etk_menu_shell_append(ETK_MENU_SHELL(main_gui->menu_bar), ETK_MENU_ITEM(main_gui->menu_item));
    main_gui->menu_item = etk_menu_item_new_with_label("Configuration");

    /*  Configuration popup menu */
    main_gui->menu = etk_menu_new();
    etk_menu_item_submenu_set(ETK_MENU_ITEM(main_gui->menu_item), ETK_MENU(main_gui->menu));
    main_gui->popup_menu_item = etk_menu_item_new_with_label("Common preferences");
    etk_menu_shell_append(ETK_MENU_SHELL(main_gui->menu), ETK_MENU_ITEM(main_gui->popup_menu_item));
    etk_signal_connect("activated", ETK_OBJECT(main_gui->popup_menu_item), ETK_CALLBACK(_commprefs_open_cb), NULL);

    etk_menu_shell_append(ETK_MENU_SHELL(main_gui->menu_bar), ETK_MENU_ITEM(main_gui->menu_item));
    main_gui->menu_item = etk_menu_item_new_with_label("Help");
    etk_menu_shell_append(ETK_MENU_SHELL(main_gui->menu_bar), ETK_MENU_ITEM(main_gui->menu_item));

    /* Toolbar */
    main_gui->toolbar = etk_toolbar_new();
    etk_box_append(ETK_BOX(main_gui->vbox), main_gui->toolbar, ETK_BOX_START, ETK_BOX_NONE, 0);
    main_gui->toolbar_button = etk_tool_button_new_with_label("Get");
    //main_gui->toolbar_button = etk_tool_button_new_from_stock(ETK_STOCK_GO_PREVIOUS);
    etk_toolbar_append(ETK_TOOLBAR(main_gui->toolbar), main_gui->toolbar_button, ETK_BOX_START);
    main_gui->toolbar_button = etk_tool_button_new_with_label("Get All");
    etk_toolbar_append(ETK_TOOLBAR(main_gui->toolbar), main_gui->toolbar_button, ETK_BOX_START);
    main_gui->separator = etk_vseparator_new();
    etk_toolbar_append(ETK_TOOLBAR(main_gui->toolbar), main_gui->separator, ETK_BOX_START);
    main_gui->toolbar_button = etk_tool_button_new_with_label("Send");
    etk_toolbar_append(ETK_TOOLBAR(main_gui->toolbar), main_gui->toolbar_button, ETK_BOX_START);
    main_gui->separator = etk_vseparator_new();
    etk_toolbar_append(ETK_TOOLBAR(main_gui->toolbar), main_gui->separator, ETK_BOX_START);
    main_gui->toolbar_button = etk_tool_button_new_with_label("Compose");
    etk_toolbar_append(ETK_TOOLBAR(main_gui->toolbar), main_gui->toolbar_button, ETK_BOX_START);
    main_gui->toolbar_button = etk_tool_button_new_with_label("Reply");
    etk_toolbar_append(ETK_TOOLBAR(main_gui->toolbar), main_gui->toolbar_button, ETK_BOX_START);
    main_gui->toolbar_button = etk_tool_button_new_with_label("Reply to all");
    etk_toolbar_append(ETK_TOOLBAR(main_gui->toolbar), main_gui->toolbar_button, ETK_BOX_START);
    main_gui->toolbar_button = etk_tool_button_new_with_label("Forward");
    etk_toolbar_append(ETK_TOOLBAR(main_gui->toolbar), main_gui->toolbar_button, ETK_BOX_START);
    main_gui->separator = etk_vseparator_new();
    etk_toolbar_append(ETK_TOOLBAR(main_gui->toolbar), main_gui->separator, ETK_BOX_START);
    main_gui->toolbar_button = etk_tool_button_new_with_label("Delete");
    etk_toolbar_append(ETK_TOOLBAR(main_gui->toolbar), main_gui->toolbar_button, ETK_BOX_START);
    main_gui->separator = etk_vseparator_new();
    etk_toolbar_append(ETK_TOOLBAR(main_gui->toolbar), main_gui->separator, ETK_BOX_START);
    main_gui->toolbar_button = etk_tool_button_new_with_label("Prev");
    etk_toolbar_append(ETK_TOOLBAR(main_gui->toolbar), main_gui->toolbar_button, ETK_BOX_START);
    main_gui->toolbar_button = etk_tool_button_new_with_label("Next");
    etk_toolbar_append(ETK_TOOLBAR(main_gui->toolbar), main_gui->toolbar_button, ETK_BOX_START);

    /* Resizeable horiz panel, folders tree and messages table/view */
    main_gui->hpaned = etk_hpaned_new();
    etk_box_append(ETK_BOX(main_gui->vbox), ETK_WIDGET(main_gui->hpaned), ETK_BOX_START, ETK_BOX_EXPAND_FILL, 0);

    /* Folders tree*/
    main_gui->folder_tree = etk_tree_new();
    etk_tree_mode_set(ETK_TREE(main_gui->folder_tree), ETK_TREE_MODE_TREE);
    etk_tree_multiple_select_set(ETK_TREE(main_gui->folder_tree), ETK_FALSE);
    etk_paned_child1_set(ETK_PANED(main_gui->hpaned), ETK_WIDGET(main_gui->folder_tree), ETK_FALSE);

    main_gui->mail_folders = etk_tree_col_new(ETK_TREE(main_gui->folder_tree), "Folders",300, 0.0);
    etk_tree_col_min_width_set(ETK_TREE_COL(main_gui->mail_folders), 300);
    etk_tree_col_model_add(main_gui->mail_folders, etk_tree_model_image_new());
    etk_tree_col_model_add(main_gui->mail_folders, etk_tree_model_text_new());

    etk_tree_build(ETK_TREE(main_gui->folder_tree));
    etk_tree_freeze(ETK_TREE(main_gui->folder_tree));
    /* Obtaining the folders tree */
    list_folders();

    /* Right place to order the tree */
    etk_tree_col_sort_set(main_gui->mail_folders, _etk_tree_compare_cb, NULL);
    etk_tree_col_sort(main_gui->mail_folders, (main_gui->mail_folders->tree->sorted_asc));

    etk_tree_thaw(ETK_TREE(main_gui->folder_tree));
    etk_tree_row_unfold(etk_tree_first_row_get(ETK_TREE(main_gui->folder_tree)));

    etk_signal_connect("row-clicked", ETK_OBJECT(main_gui->folder_tree), ETK_CALLBACK(_row_clicked_cb), NULL);

    /* Resizeable vert panel, messages table and message view */
    main_gui->vpaned = etk_vpaned_new();
    etk_paned_child2_set(ETK_PANED(main_gui->hpaned), ETK_WIDGET(main_gui->vpaned), ETK_TRUE);

    /* messages table */
    main_gui->message_tree = etk_tree_new();
    etk_tree_mode_set(ETK_TREE(main_gui->message_tree), ETK_TREE_MODE_TREE);
    etk_tree_multiple_select_set(ETK_TREE(main_gui->message_tree), ETK_TRUE);
    etk_paned_child1_set(ETK_PANED(main_gui->vpaned), ETK_WIDGET(main_gui->message_tree), ETK_TRUE);

    main_gui->messages_has_attchment = etk_tree_col_new(ETK_TREE(main_gui->message_tree),"", 10, 0.0);
    etk_tree_col_model_add(main_gui->messages_has_attchment, etk_tree_model_image_new());
    main_gui->messages_subj = etk_tree_col_new(ETK_TREE(main_gui->message_tree), "Subject", 130, 0.0);
    etk_tree_col_model_add(main_gui->messages_subj, etk_tree_model_text_new());
    main_gui->messages_from = etk_tree_col_new(ETK_TREE(main_gui->message_tree), "From", 130, 0.0);
    etk_tree_col_model_add(main_gui->messages_from, etk_tree_model_text_new());
    main_gui->messages_date = etk_tree_col_new(ETK_TREE(main_gui->message_tree), "Date", 130, 0.0);
    etk_tree_col_model_add(main_gui->messages_date, etk_tree_model_text_new());
    //messages_size = etk_tree_col_new(ETK_TREE(message_tree), "Size", 130, 0.0);
    //etk_tree_col_model_add(messages, etk_tree_model_image_new());
    //etk_tree_col_model_add(messages, etk_tree_model_text_new());		

    etk_tree_build(ETK_TREE(main_gui->message_tree));
    etk_signal_connect("row-clicked", ETK_OBJECT(main_gui->message_tree), 
    ETK_CALLBACK(_message_clicked_cb), NULL);

    main_gui->message_vbox = etk_vbox_new(ETK_FALSE, 5);
    etk_paned_child2_set(ETK_PANED(main_gui->vpaned), ETK_WIDGET(main_gui->message_vbox), ETK_TRUE);

    main_gui->from_label = etk_label_new("");
    main_gui->to_label = etk_label_new("");
    main_gui->subj_label = etk_label_new("");
    main_gui->messagebody_scroll = etk_scrolled_view_new();
    main_gui->messagebody = etk_text_view_new();
    etk_bin_child_set(ETK_BIN(main_gui->messagebody_scroll), main_gui->messagebody);
    etk_box_append(ETK_BOX(main_gui->message_vbox), ETK_WIDGET(main_gui->messagebody_scroll),
    ETK_BOX_START, ETK_BOX_EXPAND_FILL, 0);
    etk_widget_focusable_set(ETK_WIDGET(main_gui->messagebody), ETK_FALSE);

    main_gui->attachment_table = etk_tree_new();
    etk_tree_mode_set(ETK_TREE(main_gui->attachment_table), ETK_TREE_MODE_TREE);
    etk_tree_multiple_select_set(ETK_TREE(main_gui->attachment_table), ETK_FALSE);
    main_gui->attach_mime = etk_tree_col_new(ETK_TREE(main_gui->attachment_table), "MIME", 130, 0.0);
    etk_tree_col_model_add(main_gui->attach_mime, etk_tree_model_text_new());
    main_gui->attach_size = etk_tree_col_new(ETK_TREE(main_gui->attachment_table), "Size", 130, 0.0);
    etk_tree_col_model_add(main_gui->attach_size, etk_tree_model_int_new());
    main_gui->attach_name = etk_tree_col_new(ETK_TREE(main_gui->attachment_table), "Name", 130, 0.0);
    etk_tree_col_model_add(main_gui->attach_name, etk_tree_model_text_new());
    etk_tree_build(ETK_TREE(main_gui->attachment_table));
    etk_box_append(ETK_BOX(main_gui->message_vbox), ETK_WIDGET(main_gui->attachment_table), ETK_BOX_END, ETK_BOX_NONE, 0);
    etk_signal_connect("row-clicked", ETK_OBJECT(main_gui->attachment_table), ETK_CALLBACK(_mime_message_part_clicked_cb), NULL);

    main_gui->status_bar = etk_statusbar_new();
    etk_box_append(ETK_BOX(main_gui->vbox), ETK_WIDGET(main_gui->status_bar), ETK_BOX_END, ETK_BOX_NONE, 0);

    etk_widget_show_all(main_gui->win);

    etk_widget_hide(ETK_WIDGET(main_gui->attachment_table));

    main_gui->file = NULL;
    main_gui->msginfo = NULL;
}

/* Build the popup menu on attachment table (common entries) */
void build_attachment_popup_menu(MimeInfo *mimeinfo) {
    main_gui->attach_menu = etk_menu_new();
    main_gui->attach_menu_item = etk_menu_item_new_with_label("Open");
    etk_menu_shell_append(ETK_MENU_SHELL(main_gui->attach_menu), ETK_MENU_ITEM(main_gui->attach_menu_item));
    etk_signal_connect("activated", ETK_OBJECT(main_gui->attach_menu_item), ETK_CALLBACK(_mime_message_part_open_cb), mimeinfo);
    main_gui->attach_menu_item = etk_menu_item_new_with_label("Open with...");
    etk_menu_shell_append(ETK_MENU_SHELL(main_gui->attach_menu), ETK_MENU_ITEM(main_gui->attach_menu_item));
    etk_widget_disabled_set(ETK_WIDGET(main_gui->attach_menu_item), ETK_TRUE);
    main_gui->attach_menu_item = etk_menu_item_new_with_label("Save as...");
    etk_menu_shell_append(ETK_MENU_SHELL(main_gui->attach_menu), ETK_MENU_ITEM(main_gui->attach_menu_item));
    etk_signal_connect("activated", ETK_OBJECT(main_gui->attach_menu_item), ETK_CALLBACK(_mime_message_part_save_as_cb), mimeinfo);
    main_gui->attach_menu_item = etk_menu_item_new_with_label("Save all");
    etk_menu_shell_append(ETK_MENU_SHELL(main_gui->attach_menu), ETK_MENU_ITEM(main_gui->attach_menu_item));
    etk_widget_disabled_set(ETK_WIDGET(main_gui->attach_menu_item), ETK_TRUE);
}

/* Window destroying */
void _main_quit_cb(void *data) {
    etk_main_quit();
}

/* Row selected */
void _row_clicked_cb(Etk_Tree *tree, Etk_Tree_Row *row, void *data) {
    char *row_path;

    etk_paned_position_set(ETK_PANED(main_gui->hpaned), 200); //TEST

    row_path = etk_tree_row_data_get(row);
    if (row_path != NULL)
        list_messages(row_path);
    else
        etk_tree_clear(ETK_TREE(main_gui->message_tree));
}

/* Handle a click on a Open item on attachment's popup menu */
void _mime_message_part_open_cb(Etk_Menu_Item *item, void *data) {
    MimeInfo *mimeinfo;
    char *filename;

    mimeinfo = (MimeInfo *)data;

    // TODO: Check for errors!
    filename = procmime_get_tmp_file_name(mimeinfo);
    procmime_get_part(filename, main_gui->file, mimeinfo);
    procmime_execute_open_file(filename, mimeinfo->content_type);
}

/* Handle a click on a Save As item on attachment's popup menu */
void _mime_message_part_save_as_cb(Etk_Menu_Item *item, void *data) {
    Etk_Widget *btn;
    MimeInfo *mimeinfo;

    main_gui->filechooser_dialog = etk_window_new();
    etk_window_title_set(ETK_WINDOW(main_gui->filechooser_dialog), "E-Mail - Save attachment as ...");

    main_gui->filechooser_vbox = etk_vbox_new(ETK_FALSE, 0);
    main_gui->filechooser_hbox = etk_hbox_new(ETK_FALSE, 0);

    main_gui->filechooser = etk_filechooser_widget_new();
    etk_filechooser_widget_is_save_set(ETK_FILECHOOSER_WIDGET(main_gui->filechooser), ETK_TRUE);
    mimeinfo = (MimeInfo *)data;
    etk_filechooser_widget_selected_file_set(ETK_FILECHOOSER_WIDGET(main_gui->filechooser), mimeinfo->name);

    etk_container_add(ETK_CONTAINER(main_gui->filechooser_dialog), main_gui->filechooser_vbox);
    etk_container_add(ETK_CONTAINER(main_gui->filechooser_vbox), main_gui->filechooser);
    etk_container_add(ETK_CONTAINER(main_gui->filechooser_vbox), main_gui->filechooser_hbox);

    btn = etk_button_new_with_label("Save");
    etk_box_append(ETK_BOX(main_gui->filechooser_hbox), btn, ETK_BOX_END, ETK_BOX_NONE, 0);
    etk_signal_connect_swapped("clicked", ETK_OBJECT(btn), ETK_CALLBACK(_mime_message_part_save_as), mimeinfo);

    btn = etk_button_new_with_label("Cancel");
    etk_box_append(ETK_BOX(main_gui->filechooser_hbox), btn, ETK_BOX_END, ETK_BOX_NONE, 0);
    etk_signal_connect_swapped("clicked", ETK_OBJECT(btn), ETK_CALLBACK(_mime_message_part_save_as_dialog_destroy), NULL);

    etk_widget_show_all(main_gui->filechooser_dialog);
}

/* Handle a click on an attachment */
void _mime_message_part_clicked_cb(Etk_Tree *tree, Etk_Tree_Row *row,
        Etk_Event_Mouse_Up *event, void *data) {
    MimeInfo *mimeinfo;
    char *filename;
    char buf[BUFFSIZE];
    Etk_Textblock_Iter *iter;

    if (etk_tree_row_data_get(row) != NULL) {
        mimeinfo = etk_tree_row_data_get(row);
        switch (mimeinfo->mime_type) {
        case MIME_IMAGE: {
            if (event->button == 1) {
                FILE *fp;

                fp = fopen(main_gui->file, "rb");
                filename = procmime_get_tmp_file_name(mimeinfo);
                if (procmime_get_part_fp(filename, fp, mimeinfo) < 0) {
                    printf("Can't save the part\n");
                    fclose(fp);
                    exit(1);
                }
                show_image(filename);
                fclose(fp);
            } else if (event->button == 3) {
                build_attachment_popup_menu(mimeinfo);
                etk_menu_popup(ETK_MENU(main_gui->attach_menu));
            }
            break;
        }
        case MIME_APPLICATION:
        case MIME_APPLICATION_OCTET_STREAM:
        case MIME_UNKNOWN:
        case MIME_AUDIO:
        case MIME_VIDEO:
            if (event->button == 3) {
                build_attachment_popup_menu(mimeinfo);
                main_gui->attach_menu_item = etk_menu_item_new_with_label("Display as text");
                etk_menu_shell_append(ETK_MENU_SHELL(main_gui->attach_menu), ETK_MENU_ITEM(main_gui->attach_menu_item));
                etk_widget_disabled_set(ETK_WIDGET(main_gui->attach_menu_item), ETK_TRUE);
                etk_menu_popup(ETK_MENU(main_gui->attach_menu));
            }
            break;
        case MIME_MESSAGE_RFC822:
        case MIME_MULTIPART:
            if (event->button == 1) {
                FILE *fh;

                etk_textblock_clear(ETK_TEXT_VIEW(main_gui->messagebody)->textblock);
                fh = procmime_get_first_text_content(main_gui->msginfo, NULL);
                iter = etk_text_view_cursor_get(ETK_TEXT_VIEW(main_gui->messagebody));
                while (fgets(buf, sizeof(buf), fh) != NULL) {
                    etk_textblock_insert(ETK_TEXT_VIEW(main_gui->messagebody)->textblock, iter, buf, strlen(buf));
                }
                fclose(fh);
            } else if (event->button == 3) {
                build_attachment_popup_menu(mimeinfo);
                main_gui->attach_menu_item = etk_menu_item_new_with_label("Print");
                etk_menu_shell_append(ETK_MENU_SHELL(main_gui->attach_menu), ETK_MENU_ITEM(main_gui->attach_menu_item));
                etk_widget_disabled_set(ETK_WIDGET(main_gui->attach_menu_item), ETK_TRUE);
                etk_menu_popup(ETK_MENU(main_gui->attach_menu));
            }
            break;
            case MIME_TEXT:
            case MIME_TEXT_HTML:
            if (event->button == 1) {
                FILE *fp, *fh;

                fp = fopen(main_gui->file, "rb");
                etk_textblock_clear(ETK_TEXT_VIEW(main_gui->messagebody)->textblock);
                fh = procmime_get_text_content(mimeinfo, fp, NULL);
                iter = etk_text_view_cursor_get(ETK_TEXT_VIEW(main_gui->messagebody));
                while (fgets(buf, sizeof(buf), fh) != NULL) {
                    etk_textblock_insert(ETK_TEXT_VIEW(main_gui->messagebody)->textblock, iter, buf, strlen(buf));
                }
                fclose(fp);
            } else if (event->button == 3) {
                build_attachment_popup_menu(mimeinfo);
                main_gui->attach_menu_item = etk_menu_item_new_with_label("Print");
                etk_menu_shell_append(ETK_MENU_SHELL(main_gui->attach_menu), ETK_MENU_ITEM(main_gui->attach_menu_item));
                etk_widget_disabled_set(ETK_WIDGET(main_gui->attach_menu_item), ETK_TRUE);
                etk_menu_popup(ETK_MENU(main_gui->attach_menu));
            }
            break;
            default:
            break;
        }
    }
}

/* Message selected (callback) */
void _message_clicked_cb(Etk_Tree *tree, Etk_Tree_Row *row, void *data) {
    MsgInfo *msginfo;
    MimeInfo *mimeinfo;
    FILE *msgfile;
    char buf[BUFFSIZE];
    Etk_Textblock_Iter *iter;
    char *label;
    char *tmp = " ";
    char *msg_filename;

    /* With these (?) vars i can play with all headers 
     FILE *arrfile;
     Header *header;
     GPtrArray *headers;
     int i;
     */

    etk_textblock_clear(ETK_TEXT_VIEW(main_gui->messagebody)->textblock);
    iter = etk_text_view_cursor_get(ETK_TEXT_VIEW(main_gui->messagebody));
    msginfo = etk_tree_row_data_get(row);
    main_gui->msginfo = msginfo;
    msgfile = procmime_get_first_text_content(msginfo, NULL);
    msg_filename = procmsg_get_message_file_path(msginfo);
    main_gui->file = msg_filename;
    if (MSG_IS_MIME(msginfo->flags)) {
        mimeinfo = procmime_scan_message(msginfo);
        etk_tree_clear(ETK_TREE(main_gui->attachment_table));
        etk_widget_show(ETK_WIDGET(main_gui->attachment_table));
        msg_filename = procmsg_get_message_file_path(msginfo);
        fill_attachment_table(mimeinfo);
    } else {
        etk_widget_hide(ETK_WIDGET(main_gui->attachment_table));
    }

    /* Uncomment this block in order to print out all headers
     arrfile = procmsg_open_message(msginfo);
     headers = procheader_get_header_array_asis(arrfile, NULL);
     for (i = 0; i < headers->len; i++) {
     Header *header;
     header = g_ptr_array_index(headers, i);
     printf("%s: %s\n", header->name, header->body);
     }
     */
    asprintf(&label, "<b>From:</b>%s", tmp);
    etk_textblock_insert_markup(ETK_TEXT_VIEW(main_gui->messagebody)->textblock, iter, label, strlen(label));
    asprintf(&label, "%s\n", msginfo->from);
    etk_textblock_insert(ETK_TEXT_VIEW(main_gui->messagebody)->textblock, iter, label, strlen(label));
    asprintf(&label, "<b>To:</b>%s", tmp);
    etk_textblock_insert_markup(ETK_TEXT_VIEW(main_gui->messagebody)->textblock, iter, label, strlen(label));
    asprintf(&label, "%s\n", msginfo->to);
    etk_textblock_insert(ETK_TEXT_VIEW(main_gui->messagebody)->textblock, iter, label, strlen(label));
    asprintf(&label, "<b>Subject:</b> %s\n\n", msginfo->subject);
    etk_textblock_insert_markup(ETK_TEXT_VIEW(main_gui->messagebody)->textblock, iter, label, strlen(label));

    while (fgets(buf, sizeof(buf), msgfile) != NULL) {
        etk_textblock_insert(ETK_TEXT_VIEW(main_gui->messagebody)->textblock, iter, buf, strlen(buf));
    }
    etk_widget_size_recalc_queue(ETK_WIDGET(main_gui->messagebody));
    fclose(msgfile);
}

/* Fill the attachment table with MimeInfo* */
void fill_attachment_table(MimeInfo *mimeinfo) {
    if (mimeinfo->children) {
        mimeinfo = mimeinfo->children;
    }
    while (mimeinfo != NULL) {
        main_gui->attach_row = etk_tree_row_append(ETK_TREE(main_gui->attachment_table), NULL,
        main_gui->attach_mime, mimeinfo->content_type,
        main_gui->attach_size, mimeinfo->size,
        main_gui->attach_name, mimeinfo->name,
        NULL);
        etk_tree_row_data_set(main_gui->attach_row, mimeinfo);
        if (mimeinfo->children)
            fill_attachment_table(mimeinfo);
        else if (mimeinfo->sub && mimeinfo->sub->mime_type != MIME_TEXT && mimeinfo->sub->mime_type != MIME_TEXT_HTML)
            fill_attachment_table(mimeinfo->sub);
        mimeinfo = mimeinfo->next;
    }
}

/* It lists the folders under root mailbox */
void list_folders(void) {
    GList *list;
    Folder *folder;

    for (list = folder_get_list(); list != NULL; list = list->next) {
        folder = FOLDER(list->data);
        folder->klass->scan_tree(folder);
        if (folder->node)
            g_node_traverse(folder->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
                    traverse_func, NULL);
    }
}

/* Folder's tree traverse function */
gboolean traverse_func(GNode *node, gpointer data) {
    FolderItem *item;
    gchar *id;
    int node_depth;

    item = FOLDER_ITEM(node->data);
    id = folder_item_get_identifier(item);
    if (id) {
        node_depth = g_node_depth(node);
        if (node_depth == 1) {
            main_gui->stock_key = etk_stock_key_get(ETK_STOCK_PLACES_USER_HOME,
                    ETK_STOCK_SMALL);
            main_gui->root_row = etk_tree_row_append(ETK_TREE(main_gui->folder_tree), NULL,
            main_gui->mail_folders, etk_theme_icon_path_get(), main_gui->stock_key, "Mail",
            NULL);
            etk_tree_row_data_set(main_gui->child_row, NULL);
        } else if (node_depth == 2) {
            main_gui->stock_key = etk_stock_key_get(ETK_STOCK_PLACES_FOLDER, ETK_STOCK_SMALL);
            main_gui->child_row = etk_tree_row_append(ETK_TREE(main_gui->folder_tree), main_gui->root_row,
            main_gui->mail_folders, etk_theme_icon_path_get(), main_gui->stock_key, item->name, NULL);
            etk_tree_row_data_set(main_gui->child_row, item->path);
        } else if (node_depth > 2) {
            if (currdepth == node_depth) {
                if (currdepth == prevdepth)
                    main_gui->child_row = etk_tree_row_parent_get(main_gui->child_row);
                else
                    main_gui->child_row = etk_tree_row_parent_get(etk_tree_row_prev_get(main_gui->child_row));
            } else {
                while (currdepth >= node_depth) {
                    currdepth--;
                    main_gui->child_row = etk_tree_row_parent_get(main_gui->child_row);
                }
            }
            main_gui->stock_key = etk_stock_key_get(ETK_STOCK_PLACES_FOLDER, ETK_STOCK_SMALL);
            main_gui->child_row = etk_tree_row_append(ETK_TREE(main_gui->folder_tree), main_gui->child_row, main_gui->mail_folders, etk_theme_icon_path_get(), main_gui->stock_key, item->name, NULL);
            etk_tree_row_data_set(main_gui->child_row, item->path);
        }
        g_free(id);
        prevdepth = currdepth = node_depth;
    }
    return FALSE;
}

void list_messages(const gchar *folder_id) {
    FolderItem *item;
    GSList *mlist, *cur;
    const gchar *locale_date;
    gchar date_mod[80];

    etk_tree_clear(ETK_TREE(main_gui->message_tree));

    if (!folder_id)
        folder_id = "inbox";

    item = folder_find_item_from_identifier(folder_id);
    if (!item) {
        g_warning("folder item '%s' not found.\n", folder_id);
		                exit(1);
            }
            mlist = folder_item_get_msg_list(item, TRUE);

            for (cur = mlist; cur != NULL; cur = cur->next) {
                MsgInfo *msginfo = (MsgInfo *)cur->data;

                if (msginfo->date_t) {
                    procheader_date_get_localtime(date_mod, sizeof(date_mod),
                    msginfo->date_t);
                    locale_date = date_mod;
                } else if (msginfo->date)
                locale_date = msginfo->date;
                else
                locale_date = _("(No Date)");

                if (MSG_IS_MIME(msginfo->flags))
                main_gui->stock_key = etk_stock_key_get(ETK_STOCK_MAIL_ATTACHMENT, ETK_STOCK_SMALL);
                else
                main_gui->stock_key = etk_stock_key_get(ETK_STOCK_NO_STOCK, ETK_STOCK_SMALL);

                main_gui->root_row = etk_tree_row_append(ETK_TREE(main_gui->message_tree), NULL,
                main_gui->messages_has_attchment, etk_theme_icon_path_get(), main_gui->stock_key,
                main_gui->messages_subj, msginfo->subject,
                main_gui->messages_from, msginfo->from,
                main_gui->messages_date, locale_date,
                NULL);
                etk_tree_row_data_set(main_gui->root_row, msginfo);
            }
            etk_tree_row_scroll_to(etk_tree_last_row_get(ETK_TREE(main_gui->message_tree)), ETK_FALSE);
            // What happens if i comment this line?
            //procmsg_msg_list_free(mlist);
        }

        /* Callback for Save button on Save As dialog */
void _mime_message_part_save_as(void *data) {
    MimeInfo *mi;
    char *fullpath;

    mi = (MimeInfo *)data;
    asprintf(&fullpath, "%s/%s",
            etk_filechooser_widget_current_folder_get(ETK_FILECHOOSER_WIDGET(main_gui->filechooser)),
            etk_filechooser_widget_selected_file_get(ETK_FILECHOOSER_WIDGET(main_gui->filechooser)));
    //etk_object_destroy(ETK_OBJECT(main_gui->filechooser_dialog));
    if (ecore_file_exists(fullpath) == 1) {
        //open a dialog
        Etk_Widget *confirm_dialog;

        confirm_dialog = etk_message_dialog_new(ETK_MESSAGE_DIALOG_WARNING,
                ETK_MESSAGE_DIALOG_OK_CANCEL,
                "The file already exists. Overwrite it?");
        etk_signal_connect("response", ETK_OBJECT(confirm_dialog), ETK_CALLBACK(_confirm_dialog_response_cb), mi);
        etk_widget_show_all(confirm_dialog);

    } else {
        FILE *fp;
        char *filename;

        asprintf(
                &fullpath,
                "%s/%s",
                etk_filechooser_widget_current_folder_get(ETK_FILECHOOSER_WIDGET(main_gui->filechooser)),
                etk_filechooser_widget_selected_file_get(ETK_FILECHOOSER_WIDGET(main_gui->filechooser)));
        fp = fopen(main_gui->file, "rb");
        filename = procmime_get_tmp_file_name(mi);
        procmime_get_part_fp(filename, fp, mi);
        ecore_file_cp(filename, fullpath);
        fclose(fp);
        etk_object_destroy(ETK_OBJECT(main_gui->filechooser_dialog));
    }
}

/* Callback for Cancel button on Save As dialog */
void _mime_message_part_save_as_dialog_destroy(void *data) {
    etk_object_destroy(ETK_OBJECT(main_gui->filechooser_dialog));
}

void _confirm_dialog_response_cb(Etk_Object *obj, int response_id, void *data) {
    char *fullpath;
    char *filename;
    FILE *fp;
    MimeInfo *mi;

    //fullpath = (char *)data;
    mi = (MimeInfo *)data;
    switch (response_id) {
    case ETK_RESPONSE_OK:
        //_ex_image_delete_cb(e);
        fp = fopen(main_gui->file, "rb");
        filename = procmime_get_tmp_file_name(mi);
        asprintf(
                &fullpath,
                "%s/%s",
                etk_filechooser_widget_current_folder_get(ETK_FILECHOOSER_WIDGET(main_gui->filechooser)),
                etk_filechooser_widget_selected_file_get(ETK_FILECHOOSER_WIDGET(main_gui->filechooser)));
        procmime_get_part_fp(filename, fp, mi);
        ecore_file_cp(filename, fullpath);
        fclose(fp);
        etk_object_destroy(ETK_OBJECT(main_gui->filechooser_dialog));
        etk_object_destroy(ETK_OBJECT(obj));
        break;
    case ETK_RESPONSE_CANCEL:
        etk_object_destroy(ETK_OBJECT(main_gui->filechooser_dialog));
        etk_object_destroy(ETK_OBJECT(obj));
        break;
    default:
        break;
    }
}

/* Tree sort callback */
int _etk_tree_compare_cb(Etk_Tree_Col *col, Etk_Tree_Row *row1,
        Etk_Tree_Row *row2, void *data) {
    char *str1;
    char *str2;

    str1 = strdup(etk_tree_row_data_get(row1));
    str2 = strdup(etk_tree_row_data_get(row2));;

    if (strcmp(str1, "inbox") == 0)
        return -1;
    if (strcmp(str2, "inbox") == 0)
        return 1;
    if (strcmp(str1, "sent") == 0)
        return -1;
    if (strcmp(str2, "sent") == 0)
        return 1;
    if (strcmp(str1, "draft") == 0)
        return -1;
    if (strcmp(str2, "draft") == 0)
        return 1;
    if (strcmp(str1, "queue") == 0)
        return -1;
    if (strcmp(str2, "queue") == 0)
        return 1;
    if (strcmp(str1, "trash") == 0)
        return -1;
    if (strcmp(str2, "trash") == 0)
        return 1;
    return strcmp(str1, str2);
}

/* Open the Common preference gui */
void _commprefs_open_cb() {
    etk_menu_popdown(ETK_MENU(main_gui->menu));
    build_commprefs_gui();
}
